package com.ruoyi.xyq.controller;

import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.xyq.domain.Details;
import com.ruoyi.xyq.domain.WithdrawalRequest;
import com.ruoyi.xyq.mapper.DetailsMapper;
import com.ruoyi.xyq.mapper.WithdrawalMapper;
import com.ruoyi.xyq.service.IDetailsService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.xyq.domain.Withdrawal;
import com.ruoyi.xyq.service.IWithdrawalService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 提现Controller
 * 
 * @author ruoyi
 * @date 2025-05-19
 */
@RestController
@RequestMapping("/withdrawal")
public class WithdrawalController extends BaseController
{
    @Autowired
    private IWithdrawalService withdrawalService;

    @Autowired
    private WithdrawalMapper withdrawalMapper;

    @Autowired
    private DetailsMapper dmapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;


//    // 提现
//    @RequiresPermissions("xyq:withdrawal:query")
//    @GetMapping(value = "/{merchantId}/{money}")
//    public AjaxResult tixian(@PathVariable("merchantId") int merchantId,@PathVariable("money")int money) {
//        Withdrawal withdrawal = withdrawalService.selectWithdrawalById(merchantId);
//        if (withdrawal!=null){
//            withdrawal.setCurrentBalance(withdrawal.getCurrentBalance()-money);
//            withdrawal.setCashWithdrawal(withdrawal.getCashWithdrawal()+money);
//            withdrawalMapper.updateWithdrawal(withdrawal);
//        }
//        return AjaxResult.success("提现成功");
//    }

    @RequiresPermissions("xyq:withdrawal:query")
    @GetMapping("/{merchantId}/{money}")
    public AjaxResult tixian(@PathVariable("merchantId") int merchantId, @PathVariable("money") int money) {
        Withdrawal withdrawal = withdrawalService.selectWithdrawalById(merchantId);

        if (withdrawal != null) {
            // 检查余额是否充足
            if (withdrawal.getCurrentBalance() < money) {
                return AjaxResult.error("余额不足");
            }

            // 预扣余额（关键修改点）
            withdrawal.setCurrentBalance(withdrawal.getCurrentBalance() - money);
            withdrawal.setStatus(2L); // 设置状态为"处理中"
            withdrawalMapper.updateWithdrawal(withdrawal);

            // 发送消息
            WithdrawalRequest request = new WithdrawalRequest();
            request.setMerchantId(merchantId);
            request.setMoney(money);
            request.setWithdrawal(withdrawal);

            try {
                rabbitTemplate.convertAndSend("withdrawal.delay.exchange", "withdrawal.delay.routing.key", request);
            } catch (Exception e) {
                // 发送失败时回滚预扣（关键修改点）
                withdrawal.setCurrentBalance(withdrawal.getCurrentBalance() + money);
                withdrawal.setStatus(1L); // 设置为"失败"
                withdrawalMapper.updateWithdrawal(withdrawal);

                System.out.println("消息发送失败，已回滚预扣金额");
                e.printStackTrace();
                return AjaxResult.error("提现申请提交失败");
            }
        }

        return AjaxResult.success("提现申请已提交，等待审核");
    }




    /**
     * 查询提现列表
     */
    @RequiresPermissions("xyq:withdrawal:list")
    @GetMapping("/list")
    public TableDataInfo list(Withdrawal withdrawal)
    {
        startPage();
        List<Withdrawal> list = withdrawalService.selectWithdrawalList(withdrawal);
        return getDataTable(list);
    }

    /**
     * 导出提现列表
     */
    @RequiresPermissions("xyq:withdrawal:export")
    @Log(title = "提现", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Withdrawal withdrawal)
    {
        List<Withdrawal> list = withdrawalService.selectWithdrawalList(withdrawal);
        ExcelUtil<Withdrawal> util = new ExcelUtil<Withdrawal>(Withdrawal.class);
        util.exportExcel(response, list, "提现数据");
    }

    /**
     * 获取提现详细信息
     */
    @RequiresPermissions("xyq:withdrawal:query")
    @GetMapping(value = "/{merchantId}")
    public AjaxResult getInfo(@PathVariable("merchantId") int merchantId) {
        return AjaxResult.success(withdrawalService.selectWithdrawalById(merchantId));
    }

    /**
     * 新增提现
     */
    @RequiresPermissions("xyq:withdrawal:add")
    @Log(title = "提现", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Withdrawal withdrawal)
    {
        return toAjax(withdrawalService.insertWithdrawal(withdrawal));
    }

    /**
     * 修改提现
     */
    @RequiresPermissions("xyq:withdrawal:edit")
    @Log(title = "提现", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Withdrawal withdrawal)
    {
        return toAjax(withdrawalService.updateWithdrawal(withdrawal));
    }

    /**
     * 删除提现
     */
    @RequiresPermissions("xyq:withdrawal:remove")
    @Log(title = "提现", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(withdrawalService.deleteWithdrawalByIds(ids));
    }
}
